<template>
  <div class="dish-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>菜品管理</span>
          <el-button type="primary" @click="handleAdd">新增菜品</el-button>
        </div>
      </template>
      
      <!-- 搜索条件 -->
      <el-form :model="searchForm" label-width="80px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="菜品名称">
              <el-input v-model="searchForm.name" placeholder="请输入菜品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="菜品类别">
              <el-select v-model="searchForm.category" placeholder="请选择类别" clearable>
                <el-option 
                  v-for="item in categoryOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                <el-option label="上架" value="1" />
                <el-option label="下架" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="searchDish">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <el-table :data="dishList" stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="菜品名称" />
        <el-table-column prop="price" label="价格" width="120">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="available" label="库存状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.available === 1 ? 'success' : 'danger'">
              {{ scope.row.available === 1 ? '充足' : '缺货' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
              {{ scope.row.status === '1' ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="推荐" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isFeatured === 1 ? 'success' : 'info'">
              {{ scope.row.isFeatured === 1 ? '推荐' : '普通' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>
    
    <!-- 菜品编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="currentDish" label-width="100px" ref="dishForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜品名称" prop="name">
              <el-input v-model="currentDish.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number v-model="currentDish.price" :precision="2" :step="0.1" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="currentDish.category" placeholder="请选择分类" style="width: 100%">
                <el-option 
                  v-for="item in categoryOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存状态" prop="available">
              <el-select v-model="currentDish.available" placeholder="请选择库存状态" style="width: 100%">
                <el-option label="充足" :value="1" />
                <el-option label="缺货" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="currentDish.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="上架" value="1" />
                <el-option label="下架" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否推荐" prop="isFeatured">
              <el-switch
                v-model="currentDish.isFeatured"
                :active-value="1"
                :inactive-value="0"
                active-text="推荐"
                inactive-text="普通"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="菜品描述" prop="description">
          <el-input 
            v-model="currentDish.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入菜品描述" />
        </el-form-item>
        
        <el-form-item label="菜品图片" prop="imageUrl">
          <el-input v-model="currentDish.imageUrl" placeholder="请输入图片URL" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveDish">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElCard, ElTable, ElTableColumn, ElButton, ElDialog, ElForm, ElFormItem, 
         ElInput, ElInputNumber, ElSelect, ElOption, ElSwitch, ElTag, ElPagination, 
         ElMessage, ElMessageBox, ElRow, ElCol } from 'element-plus'
import { getDishList, addDish, updateDish, deleteDish, updateInventory } from '@/api/dish'

// 获取当前实例以访问全局属性
const instance = getCurrentInstance()

// 菜品列表数据
const dishList = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  status: ''
})

// 分类选项
const categoryOptions = ref([
  { label: '热菜', value: '热菜' },
  { label: '凉菜', value: '凉菜' },
  { label: '主食', value: '主食' },
  { label: '汤类', value: '汤类' },
  { label: '饮品', value: '饮品' },
  { label: '甜品', value: '甜品' }
])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 当前编辑的菜品
const currentDish = reactive({
  id: 0,
  name: '',
  price: 0,
  category: '',
  description: '',
  imageUrl: '',
  available: 1,
  status: '1',
  isFeatured: 0
})

// 处理新增菜品
const handleAdd = () => {
  dialogTitle.value = '新增菜品'
  isEdit.value = false
  // 重置表单
  Object.assign(currentDish, {
    id: 0,
    name: '',
    price: 0,
    category: '',
    description: '',
    imageUrl: '',
    available: 1,
    status: '1',
    isFeatured: 0
  })
  dialogVisible.value = true
}

// 处理编辑菜品
const handleEdit = (dish) => {
  dialogTitle.value = '编辑菜品'
  isEdit.value = true
  // 填充表单数据
  Object.assign(currentDish, dish)
  dialogVisible.value = true
}

// 保存菜品
const saveDish = async () => {
  try {
    if (isEdit.value) {
      // 编辑操作
      const res = await updateDish(currentDish)
      if (res.code === 200) {
        ElMessage.success('编辑菜品成功')
        dialogVisible.value = false
        loadDishList()
      } else {
        ElMessage.error(res.message || '编辑菜品失败')
      }
    } else {
      // 新增操作
      const res = await addDish(currentDish)
      if (res.code === 200) {
        ElMessage.success('新增菜品成功')
        dialogVisible.value = false
        loadDishList()
      } else {
        ElMessage.error(res.message || '新增菜品失败')
      }
    }
  } catch (error) {
    ElMessage.error('操作失败：' + error.message)
  }
}

// 处理删除菜品
const handleDelete = (dish) => {
  ElMessageBox.confirm(`确定要删除菜品"${dish.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteDish(dish.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        loadDishList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败：' + error.message)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 搜索菜品
const searchDish = () => {
  pagination.currentPage = 1
  loadDishList()
}

// 重置搜索条件
const resetSearch = () => {
  searchForm.name = ''
  searchForm.category = ''
  searchForm.status = ''
  pagination.currentPage = 1
  loadDishList()
}

// 分页相关处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadDishList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadDishList()
}

// 加载菜品列表
const loadDishList = async () => {
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      name: searchForm.name || undefined,
      category: searchForm.category || undefined,
      status: searchForm.status || undefined
    }
    
    const res = await getDishList(params)
    if (res.code === 200) {
      dishList.value = res.data.list || res.data
      pagination.total = res.data.total || dishList.value.length
    } else {
      ElMessage.error(res.message || '获取菜品列表失败')
    }
  } catch (error) {
    ElMessage.error('获取菜品列表失败：' + error.message)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  loadDishList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>